package main

import (
	"geek-cloud-native/chapter04-0925/global"
	"geek-cloud-native/chapter04-0925/initializers"
	"geek-cloud-native/chapter04-0925/src/routers"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
)

func init() {
	err := initializers.SetupFlag()
	if err != nil {
		log.Fatalf("initializers.SetupFlag error: %s", err)
	}
	err = initializers.SetupConfigs()
	if err != nil {
		log.Fatalf("initializers.SetupConfigs error: %s", err)
	}
	err = initializers.SetupLogger()
	if err != nil {
		log.Fatalf("initializers.SetupLogger error：%s", err)
	}
}

//go:generate go env -w GO111MODULE=on
//go:generate go env -w GOPROXY=https://goproxy.cn,direct
//go:generate go mod tidy
//go:generate go mod download

// @title 简单的HTTP服务
// @version v1.0
// @description 实现一个简单的HTTP服务
// @termsOfService https://gitee.com/coolops/geek-cloud-native/chapter04-0925
func main() {
	// 获取Version变量
	getVersion := os.Getenv("VERSION")
	if getVersion != "" {
		global.ServerSetting.Version = getVersion
	}
	if global.Port != "" {
		global.ServerSetting.HttpPort = global.Port
	}

	// 注册路由
	router := routers.NewRouter()
	s := &http.Server{
		Handler:      router,
		Addr:         ":" + global.ServerSetting.HttpPort,
		ReadTimeout:  global.ServerSetting.ReadTimeout,
		WriteTimeout: global.ServerSetting.WriteTimeout,
	}

	// 启动服务
	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("s.ListenAndServer err: %v", err)
		}
	}()
	global.Logger.Info("service started ......")
	// 等待中断信号
	quit := make(chan os.Signal)
	// 接收syscall.SIGINT和syscall.SIGTERM信号
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	global.Logger.Info("Shutting down server ......")
}
